<template>
  <div class="notice-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>通知公告</span>
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增公告</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="公告标题">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入公告标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="公告类型">
          <el-select v-model="queryParams.type" placeholder="请选择公告类型" clearable style="width: 200px">
            <el-option label="通知" value="1" />
            <el-option label="公告" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
            <el-option label="正常" value="0" />
            <el-option label="关闭" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 通知列表 -->
      <el-table
        v-loading="loading"
        :data="noticeList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :row-class-name="tableRowClassName"
        table-layout="auto"
      >
        <el-table-column label="编号" width="60" align="center">
          <template #default="{ $index }">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="title" label="公告标题" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column prop="type" label="公告类型" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag 
              :type="row.type === '1' ? 'warning' : 'success'"
              effect="light"
              size="small"
            >
              {{ row.type === '1' ? '通知' : '公告' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag 
              :type="row.status === '1' ? 'success' : 'info'"
              effect="light"
              size="small"
            >
              {{ row.status === '1' ? '正常' : '关闭' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建者" width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">修改</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 添加/修改对话框 -->
      <el-dialog
        :title="dialog.title"
        v-model="dialog.visible"
        width="700px"
        append-to-body
      >
        <el-form ref="noticeFormRef" :model="noticeForm" :rules="rules" label-width="100px">
          <el-form-item label="公告标题" prop="title">
            <el-input v-model="noticeForm.title" placeholder="请输入公告标题" />
          </el-form-item>
          <el-form-item label="公告类型" prop="type">
            <el-select v-model="noticeForm.type" placeholder="请选择公告类型" style="width: 100%">
              <el-option label="通知" value="1" />
              <el-option label="公告" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="noticeForm.status">
              <el-radio label="0">关闭</el-radio>
              <el-radio label="1">正常</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input
              v-model="noticeForm.content"
              type="textarea"
              placeholder="请输入内容"
              :rows="6"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialog.visible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 查看对话框 -->
      <el-dialog
        title="公告详情"
        v-model="viewDialog.visible"
        width="700px"
        append-to-body
      >
        <el-descriptions :column="2" border>
          <el-descriptions-item label="公告标题" :span="2">{{ viewDialog.data.title }}</el-descriptions-item>
          <el-descriptions-item label="公告类型">
            <el-tag :type="viewDialog.data.type === '1' ? 'warning' : 'success'" effect="light">
              {{ viewDialog.data.type === '1' ? '通知' : '公告' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="viewDialog.data.status === '1' ? 'success' : 'info'" effect="light">
              {{ viewDialog.data.status === '1' ? '正常' : '关闭' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建者">{{ viewDialog.data.creator }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ viewDialog.data.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ viewDialog.data.updateTime }}</el-descriptions-item>
          <el-descriptions-item label="公告内容" :span="2">
            <div class="notice-content">{{ viewDialog.data.content }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getNoticesByPage, addNotice, updateNotice, deleteNotice } from '@/api/notice'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  title: '',
  type: '',
  status: ''
})

// 数据相关
const loading = ref(false)
const total = ref(0)
const noticeList = ref([])

// 对话框相关
const dialog = reactive({
  title: '',
  visible: false
})

const viewDialog = reactive({
  visible: false,
  data: {}
})

// 表单对象
const noticeForm = reactive({
  id: undefined,
  title: '',
  type: '',
  status: '0',
  content: ''
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入公告内容', trigger: 'blur' }]
}

// 表单引用
const noticeFormRef = ref(null)

// 查询列表
const handleQuery = async () => {
  try {
    loading.value = true
    const res = await getNoticesByPage({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      title: queryParams.title,
      type: queryParams.type,
      status: queryParams.status
    })
    
    if (res.success) {
      noticeList.value = res.data.list
      total.value = res.data.total
    } else if (!res._showError) {
      ElMessage.error(res.msg || '获取公告列表失败')
    }
  } catch (error) {
    console.error('获取公告列表失败：', error)
    if (!error._showError) {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '获取公告列表失败')
      } else {
        ElMessage.error('获取公告列表失败，请稍后重试')
      }
    }
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.title = ''
  queryParams.type = ''
  queryParams.status = ''
  queryParams.pageNum = 1
  handleQuery()
}

// 新增公告
const handleAdd = () => {
  dialog.title = '新增公告'
  dialog.visible = true
  // 重置表单数据，确保响应性
  noticeForm.id = undefined
  noticeForm.title = ''
  noticeForm.type = ''
  noticeForm.status = '0'
  noticeForm.content = ''
}

// 修改公告
const handleEdit = (row) => {
  dialog.title = '修改公告'
  dialog.visible = true
  // 使用深拷贝确保不会直接修改原数据
  Object.assign(noticeForm, JSON.parse(JSON.stringify(row)))
}

// 查看公告
const handleView = (row) => {
  viewDialog.data = row
  viewDialog.visible = true
}

// 删除公告
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('是否确认删除该公告？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteNotice(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      handleQuery()
    } else if (!res._showError) {
      ElMessage.error(res.msg || '删除公告失败')
    }
  } catch (error) {
    if (error !== 'cancel' && !error._showError) {
      console.error('删除公告失败：', error)
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '删除公告失败')
      } else {
        ElMessage.error('删除公告失败，请稍后重试')
      }
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 使用ref正确获取表单引用
    if (!noticeFormRef.value) return
    
    // 表单验证
    await noticeFormRef.value.validate()
    
    let res
    if (noticeForm.id) {
      // 修改操作
      res = await updateNotice(noticeForm)
    } else {
      // 新增操作
      res = await addNotice(noticeForm)
    }
    
    if (res.success) {
      ElMessage.success(dialog.title + '成功')
      dialog.visible = false
      // 重置表单验证状态
      noticeFormRef.value.resetFields()
      handleQuery()
    } else if (!res._showError) {
      ElMessage.error(res.msg || dialog.title + '失败')
    }
  } catch (error) {
    console.error(dialog.title + '失败：', error)
    if (!error._showError) {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || dialog.title + '失败')
      } else {
        ElMessage.error(dialog.title + '失败，请稍后重试')
      }
    }
  }
}

// 分页方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  handleQuery()
}

// 表格行样式
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? '' : 'row-stripe'
}

// 初始化
onMounted(() => {
  handleQuery()
})
</script>

<style scoped>
.notice-container {
  width: 100%;
  overflow: hidden;
  display: flex;
}

.box-card {
  flex: 1;
  margin: 0;
  height: 100%;
  border-radius: 0;
  box-shadow: none;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 15px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 15px 20px;
  box-sizing: border-box;
  width: 100%;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
  width: 100% !important;
}

:deep(.el-table__inner-wrapper) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.row-stripe {
  background-color: #fafafa;
}

.notice-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style> 